package com.tolerate.managespringboot.exception;


import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理类
 */
// ControllerAdvice 拦截那些controller
// annotations = {RestController.class}:拦截,类上加了RestController的控制器
@ControllerAdvice
@ResponseBody// 将对象转为json数据(自动完成)
@Slf4j
public class ExceptionAdvice {

    /**
     * 处理业务异常,以后有关业务的异常抛出，就使用 throw  new  BusinessException
     *
     * @param ex
     * @return
     */
//    @ExceptionHandler(BusinessException.class)
//    public Result businessExceptionHandler(BusinessException ex) {
//        log.error("异常信息：{}", ex.getMessage());
//        return Result.error(ex.getCode(), ex.getMessage());
//    }

    /**
     * 异常处理方法，处理无法预见的异常
     * ExceptionHandler：声明要处理那个异常   Exception 所有异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity exceptionHandler(Exception ex) {
        log.error("异常信息：{}", ex.getMessage());
        // 直接将异常信息返回给前端
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex.getMessage().toString());
    }

    //   ResponseEntity 通过直接设置响应状态码和响应数据
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity handlerException(BusinessException ex) {
        System.out.println("异常信息：" + ex.getMessage());
        return ResponseEntity.status(ex.getCode()).body(ex.getMessage());
    }
}
